package com.jielin.handling.service.record.impl;

import com.jielin.handling.entity.record.RecordDetailed;
import com.jielin.handling.entity.record.RecordDetailedAppVo;
import com.jielin.handling.entity.room.RoomInformation;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.mapper.record.RecordDetailedMapper;
import com.jielin.handling.mapper.record.RecordStopMapper;
import com.jielin.handling.mapper.room.RoomInformationMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.mapper.unit.UnitMapper;
import com.jielin.handling.service.record.RecordDetailedService;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.StringUtil;
import com.jielin.handling.util.pdfutil.PDFReport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RecordDetailedServiceimpl implements RecordDetailedService {
    @Autowired
    private RecordDetailedMapper recordDetailedMapper;
    @Autowired
    private TSuspecMapper suspecMapper;
    @Autowired
    private RecordStopMapper recordStopMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private RoomInformationMapper roomInformationMapper;

    @Override
    public List<RecordDetailed> findAllDetailed() {
        return recordDetailedMapper.findAllDetailed();
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int addDetailed(RecordDetailed recordDetailed, String ip) {
        log.info("RecordDetailedService事务start...");
        int i = -1;
        try {
            TSuspec t = new TSuspec();
            t.setId(recordDetailed.getSuspectid());
            t.setSuspectState("6");
            suspecMapper.updateState(t);// 修改人员状态为 审讯，开始笔录
            // 没有传入房间信息，则去通过ip去查询
            if (StringUtil.isEmpty(recordDetailed.getHomeid())) {
                RoomInformation roomInformation = roomInformationMapper.findCameraInfoByRoomComputerIp(ip);
                if (roomInformation != null) {
                    recordDetailed.setHomeid(roomInformation.getId());
                    recordDetailed.setHomename(roomInformation.getRoomname());
                }
            }
            recordDetailedMapper.addDetailed(recordDetailed);// 初始化新增笔录信息
            i = 1;
        } catch (Exception e) {
            log.info("RecordDetailedService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return i;
    }

    @Override
    public int updateDetailed(RecordDetailed recordDetailed) {
        return recordDetailedMapper.updateDetailed(recordDetailed);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public RecordDetailed findDetailedById(String detailedId) {
        RecordDetailed r = null;
        try {
            r = recordDetailedMapper.findDetailedById(detailedId);
            if (r != null && !StringUtil.isEmpty(r.getContent())) {
                String s = r.getContent();
                s = s.replaceAll("\r|\n|\t", "");
                s = s.replace("<p class=\"qa-item q-item\">", "<p class='qa-item q-item'>");
                s = s.replace("<p class=\"qa-item a-item\">", "<p class='qa-item a-item'>");
                r.setContent(s);
                // 查询嫌疑人姓名
                TSuspec suspect = suspecMapper.selectByPrimaryKey(r.getSuspectid());
                r.setSuspectname(suspect == null ? "无数据" : suspect.getName());
            }
        } catch (Exception e) {
            log.info("RecordDetailedService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return r;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public List<RecordDetailed> findDetailedBySuspectId(String suspectId, String cordId) {
        List<RecordDetailed> list = new ArrayList<RecordDetailed>();
        try {
            if (!StringUtil.isEmpty(cordId)) {// 根据嫌疑人证件号码查询历史笔录信息
                List<String> suspectIdlist = suspecMapper.findIdByCordId(cordId);
                if (suspectIdlist.size() > 0) {
                    for (String thissuspectId : suspectIdlist) {
                        list.addAll(recordDetailedMapper.findDetailedBySuspectId(thissuspectId));
                        for (RecordDetailed recordDetailed : list) {
                            if (recordDetailed != null && !StringUtil.isEmpty(recordDetailed.getContent())) {
                                String s = recordDetailed.getContent();
                                s = s.replaceAll("\r|\n|\t", "");
                                s = s.replace("<p class=\"qa-item q-item\">", "<p class='qa-item q-item'>");
                                s = s.replace("<p class=\"qa-item a-item\">", "<p class='qa-item a-item'>");
                                // 将转义字符去掉
                                recordDetailed.setContent(s);
                                // 查询嫌疑人姓名
                                TSuspec suspect = suspecMapper.selectByPrimaryKey(recordDetailed.getSuspectid());
                                recordDetailed.setSuspectname(suspect == null ? "无数据" : suspect.getName());
                            }
                            recordDetailed.setUsrTime(DateUtil.intToMinutesAndSeconds(recordDetailed.getUsrdate()));
                        }
                    }
                }
            } else {
                list = recordDetailedMapper.findDetailedBySuspectId(suspectId);
                if (list.size() == 0) {
                    return list;
                }
                for (RecordDetailed recordDetailed : list) {
                    if (recordDetailed != null && !StringUtil.isEmpty(recordDetailed.getContent())) {
                        String s = recordDetailed.getContent();
                        s = s.replaceAll("\r|\n|\t", "");
                        s = s.replace("<p class=\"qa-item q-item\">", "<p class='qa-item q-item'>");
                        s = s.replace("<p class=\"qa-item a-item\">", "<p class='qa-item a-item'>");
                        // 将转义字符去掉
                        recordDetailed.setContent(s);
                    }
                    recordDetailed.setUsrTime(DateUtil.intToMinutesAndSeconds(recordDetailed.getUsrdate()));
                    // 查询嫌疑人姓名
                    TSuspec suspect = suspecMapper.selectByPrimaryKey(recordDetailed.getSuspectid());
                    recordDetailed.setSuspectname(suspect == null ? "无数据" : suspect.getName());// 嫌疑人姓名
                    recordDetailed.setStopNum(recordStopMapper.findStopNumByRecordDetailedId(recordDetailed.getId()));// 笔录暂停次数
                }
            }
        } catch (Exception e) {
            log.info("RecordDetailedService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return list;
    }

    @Override
    public String printDetailed(String detailedId, String suspectId, String watermark, String number, String askunit,
                                String recordunit, String fileString, Boolean wantWatermark) throws Exception {
        log.info("根据嫌疑人id与笔录id开始查询");
        // 获取嫌疑人信息
        TSuspec sus = suspecMapper.selectByPrimaryKey(suspectId);
        if (sus == null) {
            sus = new TSuspec();
        }
        // 获取当前笔录信息
        RecordDetailed red = recordDetailedMapper.findDetailedById(detailedId);
        if (red == null) {
            red = new RecordDetailed();
        }
        String s = "";
        List<String> leftlist = new ArrayList<>();
        List<String> rightlist = new ArrayList<>();
        if (red != null && !StringUtil.isEmpty(red.getContent())) {
            s = red.getContent();
            // String s =
            // "<p>问：你叫什么名字？</p><p>答：我叫张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p><p>问：你叫什么名字？</p><p>答：我叫张三。</p><p>问：你家里几口人？</p><p>答：算上我4个人。</p>";
            s = s.replaceAll("\r|\n|\t", "");
            s = s.replace("<p class=\"qa-item q-item\">", "");
            s = s.replace("<p class=\"qa-item a-item\">", "");
            s = s.replace("&nbsp;", " ");
            String[] strs = s.split("</p>");
            for (int i = 0; i < strs.length; i++) {
                String row = strs[i];
                int i1 = row.indexOf("：");
                String one1 = row.substring(0, i1 + 1);
                String two1 = row.substring(i1 + 1, row.length());
                leftlist.add(one1);
                rightlist.add(two1);
            }
        }

        log.info("开始生产pdf");
        PDFReport ppt = new PDFReport();

        // TSuspec suspec = new TSuspec();
        // suspec.setName("张三");
        // suspec.setAge(25);
        // suspec.setSex(0);
        // suspec.setIsdeputy(0);
        // suspec.setIdValue("362202199305235510");
        // suspec.setPhone("15377074555");
        // suspec.setAddress("湖北省武汉市青山区团结大道仁和路老岸88号");
        // suspec.setHousehold("湖北省武汉市江岸区88号");
        // suspec.setGototype("1");// 口头传唤
        // suspec.setPersonnelType("0304");// 人员类别 0301:犯罪嫌疑人 0302:违法行为人 0303:证人
        // 0304:受害人
        // // 嫌疑人到达时间
        // suspec.setCreateDate(new Date());
        // suspec.setModifyDate(new Date());
        // RecordDetailed rd = new RecordDetailed();
        // rd.setStartdate(new Date());
        // rd.setEnddate(new Date());
        // rd.setAskpolicename("王小明");
        // rd.setHomename("1号询问室");
        // rd.setRecordpolicename("王晓红");
        // ppt.writePdf("询问/讯问笔录", zzz.toString(), null, null, "杰霖科技", "2", leftlist,
        // rightlist, suspec, rd, "洪山派出所", "洪山派出所");

        String unitNamePoliceNamePoliceCode = null;
        if (wantWatermark) {
            // 水印内容：单位名称-警员名称-警号
            unitNamePoliceNamePoliceCode = suspecMapper.selectUnitNamePoliceNamePoliceCodeBySusId(suspectId);
        }
        String path = ppt.writePdf(null, null, null, null, unitNamePoliceNamePoliceCode, number, leftlist, rightlist, sus, red, askunit,
                recordunit, fileString);
        // ppt.addWaterMark("D:\\ITextTest.pdf", "D:\\ITextTest1.pdf", "万日", 400, 400,
        // "", 100, 100);
        // ppt.addWaterMark("D:\\ITextTest.pdf", "D:\\ITextTest1.pdf", "万日", 500, 980);
        // 保存pdf文件到笔录详细信息中
        recordDetailedMapper.updateDetailedPdfPath(RecordDetailed.builder().id(detailedId).pdfPath(path).build());
        log.info("生成完成pdf文件，返回文件路径");
        return path;
    }

    @Override
    public RecordDetailedAppVo findDetailedBySuspectIdAndNum(String suspectId, int number) {
        if (StringUtil.isEmpty(suspectId)) {
            return null;
        }
        RecordDetailedAppVo rdaVo = recordDetailedMapper.findDetailedAppVoBySuspectId(suspectId,
                number > 1 ? number - 1 : 0, number > 1 ? number : 1);
        if (rdaVo != null && !StringUtil.isEmpty(rdaVo.getContent())) {
            String s = rdaVo.getContent();
            s = s.replaceAll("\r|\n|\t", "");
            s = s.replace("<p class=\"qa-item q-item\">", "<p class='qa-item q-item'>");
            s = s.replace("<p class=\"qa-item a-item\">", "<p class='qa-item a-item'>");
            // 将转义字符去掉
            rdaVo.setContent(s);
        }
        return rdaVo;
    }

    @Override
    public String printListDetailed(String detailedId, String suspectId, String watermark, String fileString) throws Exception {
        // 获取嫌疑人信息
        TSuspec sus = suspecMapper.selectByPrimaryKey(suspectId);
        if (sus == null) {
            sus = new TSuspec();
        }
        // 获取当前笔录信息
        RecordDetailed red = recordDetailedMapper.findDetailedById(detailedId);
        if (red == null) {
            red = new RecordDetailed();
        }
        String s = "";
        List<String> leftlist = new ArrayList<>();
        List<String> rightlist = new ArrayList<>();
        if (red != null && !StringUtil.isEmpty(red.getContent())) {
            s = red.getContent();
            s = s.replaceAll("\r|\n|\t", "");
            s = s.replace("<p class=\"qa-item q-item\">", "");
            s = s.replace("<p class=\"qa-item a-item\">", "");
            s = s.replace("&nbsp;", " ");
            String[] strs = s.split("</p>");
            for (int i = 0; i < strs.length; i++) {
                String row = strs[i];
                int i1 = row.indexOf("：");
                String one1 = row.substring(0, i1 + 1);
                String two1 = row.substring(i1 + 1, row.length());
                leftlist.add(one1);
                rightlist.add(two1);
            }
        }
        // 查询第几次笔录
        int searchNumber = recordDetailedMapper.findDetailedNumBySuspectId(suspectId).indexOf(red.getCreateDate());
        String number = String.valueOf((searchNumber == -1 ? 0 : searchNumber) + 1);
        // 查询询问的人的工作单位名称
        String askunit = unitMapper.findUnitNameByPoliceId(red.getAskpoliceid().split(","));
        // 查询记录人的工作单位名称
        String recordunit = unitMapper.findUnitNameByPoliceId(new String[]{red.getRecordpoliceid()});
        // 笔录的base64签名
//        String fileString = "";

        log.info("开始生产pdf");
        PDFReport ppt = new PDFReport();
        String path = ppt.writePdf(null, null, null, null, watermark, number, leftlist, rightlist, sus, red, askunit,
                recordunit, fileString);
        recordDetailedMapper.updateDetailedPdfPath(RecordDetailed.builder().id(detailedId).pdfPath(path).build());
        log.info("生成完成pdf文件，返回文件路径");
        return path;
    }

}
